package com.hjimi.ski.view.widget;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2019/1/31 0031.
 */

public class DialogViewHelper {
    private View mContentView = null;
    //软引用 防止霸气侧漏
    private SparseArray<WeakReference<View>> mViews;

    public DialogViewHelper(Context context, int viewLayoutResId) {
        this();
        mContentView = LayoutInflater.from(context).inflate(viewLayoutResId,null);
    }

    public DialogViewHelper() {
        mViews = new SparseArray<>();
    }

    /**
     * 设置布局
     * @param contentView
     */
    public void setContentView(View contentView) {
        this.mContentView = contentView;
    }

    /**
     * 设置文本
     * @param viewId
     * @param charSequence
     */
    public void setText(int viewId, CharSequence charSequence) {
        // 每次都findViewById    减少findViewById的次数
        TextView tv = getView(viewId);
        if(tv != null){
            tv.setText(charSequence);
        }
    }

    /**
     * 设置点击事件
     * @param viewId
     * @param listener
     */
    public void setOnClickListener(int viewId, View.OnClickListener listener) {
        View view = getView(viewId);
        if(view != null){
            view.setOnClickListener(listener);
        }
    }

    public <T extends View> T getView(int viewId) {
        View view = null;
        //通过viewId找View
        WeakReference<View> viewReference = mViews.get(viewId);
        if(viewReference != null){
            //找到 取出view
            view = viewReference.get();
        }
        if(view == null){
            //没找到 去findViewById
            view = mContentView.findViewById(viewId);
            if(view!=null){
                //找到之后如果不为空 将view放入
                mViews.put(viewId,new WeakReference<>(view));
            }
        }
        return (T)view;
    }

    /**
     * 获取Content的View
     * @return
     */
    public View getContentView() {
        return mContentView;
    }
}
